package battleship;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Attempt to log the user in using the parameters in the given request.
	 * 
	 * @param request
	 *            the Servlet request object.
	 * @return true iff successful.
	 * @throws SQLException
	 */
	public static boolean login(HttpServletRequest request) throws SQLException {
		final Connection con = Database.open();
		final String uid = request.getParameter(Constants.ATTR_UID);
		final PreparedStatement ps = con
				.prepareStatement("select * from User where uid=binary ?");
		ps.setString(1, uid);
		final ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			final HttpSession session = request.getSession(true);
			session.setAttribute(Constants.ATTR_UID, uid);
			session.setAttribute(Constants.ATTR_NICKNAME,
					rs.getString("nickname"));
			return true;
		}
		return false;
	}

	/**
	 * Log the user out.
	 * 
	 * @param session
	 *            the HTTP session object.
	 * @return null if the user isn't logged in; otherwise, the nickname of the
	 *         user as a String.
	 */
	public static Object logout(HttpSession session) {
		if (session != null) {
			final Object nickname = session
					.getAttribute(Constants.ATTR_NICKNAME);
			session.removeAttribute(Constants.ATTR_UID);
			session.removeAttribute(Constants.ATTR_NICKNAME);
			return nickname;
		}
		return null;
	}
}
